package com.hengtiansoft.lfy.chart.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.action.UpdateGroupAvatarJson;
import com.hengtiansoft.lfy.chart.adapter.ContactAdapter;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.bean.getGroupAvatarByUsernameBean;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.chart.db.UserDao;
import com.hengtiansoft.lfy.chart.domain.FriendsUser;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hengtiansoft.lfy.widget.Sidebar;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupManager;
import com.hyphenate.exceptions.HyphenateException;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 修改群成员页面
 */
public class GroupPickContactsActivity extends BaseActivity {
    private static final String TAG = "GroupPickContactsActivity";
    private ListView listView;
    /** 是否为一个新建的群组 */
    protected boolean isCreatingNewGroup;
    /** 是否为单选 */
    private boolean isSignleChecked = false;
    private PickContactAdapter contactAdapter;
    /** group中一开始就有的成员 */
    private List<String> exitingMembers;
    // private HorizontalListView mHlvAvatar;
    // private HorizontalListViewAdapter mHorizontalListViewAdapter;
    private GridView mGvAvatar;
    private List<String> members = new ArrayList<String>();
    private RelativeLayout mRlGroup;
    private ProgressDialog progressDialog;
    ImageButton clearSearch;
    EditText query;
    private LinearLayout mLlHint;
    private InputMethodManager inputMethodManager;
    private String from;
    private Context mContext;
    private EMGroup emGroup;
    private UserDao userDao;
    private int avatarSize = 0;
    private Button mBtnSave;
    private boolean hideEnter = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_group_pick_contacts);
        inputMethodManager = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        // String groupName = getIntent().getStringExtra("groupName");
        mBtnSave = (Button) findViewById(R.id.btn_save);
        String groupId = getIntent().getStringExtra("groupId");
        from = getIntent().getStringExtra("from");
        userDao = new UserDao(this);
        if (groupId == null) {// 创建群组
            isCreatingNewGroup = true;
            mBtnSave.setText(getString(R.string.button_save));
        } else {
            mBtnSave.setText(getString(R.string.register_mobile_submit));
            // 获取此群组的成员列表
            EMGroup group = EMClient.getInstance().groupManager().getGroup(groupId);
            exitingMembers = group.getMembers();
            for (int i = 0; i < exitingMembers.size(); i++) {
                members.add(exitingMembers.get(i));
            }
            avatarSize = exitingMembers.size();
        }
        if (exitingMembers == null)
            exitingMembers = new ArrayList<String>();
        // 获取好友列表
        final List<FriendsUser> alluserList = new ArrayList<FriendsUser>();
        for (FriendsUser user : ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                .getContactList().values()) {
            if (!user.getUsername().equals(Constants.NEW_FRIENDS_USERNAME)
                    & !user.getUsername().equals(Constants.GROUP_USERNAME)
                    & !user.getUsername().equals(Constants.CHAT_ROOM)
                    & !user.getUsername().equals(Constants.CHAT_ROBOT))
                alluserList.add(user);
        }
        // 对list进行排序
        Collections.sort(alluserList, new Comparator<FriendsUser>() {
            @Override
            public int compare(FriendsUser lhs, FriendsUser rhs) {
                return (lhs.getHeader().compareTo(rhs.getHeader()));

            }
        });

        // mGvAvatar = (GridView) findViewById(R.id.gv_avatar);
        // mHlvAvatar = (HorizontalListView) findViewById(R.id.hlv_avatar);
        // mHorizontalListViewAdapter = new HorizontalListViewAdapter(
        // GroupPickContactsActivity.this, members);
        // mHlvAvatar.setAdapter(mHorizontalListViewAdapter);
        listView = (ListView) findViewById(R.id.list);
        contactAdapter = new PickContactAdapter(this,
                R.layout.row_contact_with_checkbox, alluserList);
        listView.setAdapter(contactAdapter);
        ((Sidebar) findViewById(R.id.sidebar)).setListView(listView);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
                checkBox.toggle();

            }
        });
        mRlGroup = (RelativeLayout) findViewById(R.id.rl_goto_group);
        mRlGroup.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                startActivity(new Intent(GroupPickContactsActivity.this,
                        GroupsActivity.class));
            }
        });
        mLlHint = (LinearLayout) findViewById(R.id.ll_hint);
        // 搜索框
        query = (EditText) findViewById(R.id.query);
        clearSearch = (ImageButton) findViewById(R.id.search_clear);
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                contactAdapter.getFilter().filter(s);
                if (s.length() > 0) {
                    mLlHint.setVisibility(View.GONE);
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    mLlHint.setVisibility(View.VISIBLE);
                    clearSearch.setVisibility(View.INVISIBLE);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = getWindow().getDecorView().getRootView().getHeight() - rect.bottom;
                if (rootInvisibleHeight < 300) {
                    if(hideEnter) {
                        getWindow().getDecorView().requestFocus();
                        hideEnter=false;
                    }
                }else{

                    hideEnter=true;
                }
            }
        });
    }

    void hideSoftKeyboard() {
        if (getWindow()
                .getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(
                        getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // @Override
    // public void onWindowFocusChanged(boolean hasFocus) {
    // super.onWindowFocusChanged(hasFocus);
    // Log.i(TAG, "头像个数：" + avatarSize);
    // if (hasFocus) {
    // mHlvAvatar.setSelection(avatarSize - 1);
    // }
    // }

    /**
     * 确认选择的members
     * 
     * @param v
     */
    public void save(View v) {
        String[] members = getToBeAddMembers()
                .toArray(new String[0]);
        if (getIntent().getStringExtra("groupId") == null) {
            if (members.length < 2) {
                Toast.makeText(GroupPickContactsActivity.this, getResources().getString(R.string.group_tit), Toast.LENGTH_LONG).show();
                return;
            }
        }
        if (from != null) {
            String st1 = getResources()
                    .getString(R.string.Is_to_create_a_group_chat);
            final String st2 = getResources()
                    .getString(R.string.Failed_to_create_groups);
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage(st1);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 调用sdk创建群组方法
                    // String groupName =
                    // groupNameEditText.getText().toString().trim();
                    // String desc = introductionEditText.getText().toString();
                    String[] members = getToBeAddMembers()
                            .toArray(new String[0]);
                    String name = "";
                    int size = members.length;
                    if (size > 4) {
                        for (int i = 0; i < 4; i++) {
                            if (i > 0) {
                                name = name + "、";
                            }
                            name = name + members[i];
                        }
                    } else {
                        for (int i = 0; i < size; i++) {
                            if (i > 0) {
                                name = name + "、";
                            }
                            name = name + members[i];
                        }
                    }
                    try {
                        // 创建不公开群
                       /* emGroup = EMGroupManager.getInstance()
                                .createPrivateGroup(name, getString(R.string.Introduction), members, true,
                                        200);*/

                        EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions();
                        option.maxUsers = 200;
                        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePrivateMemberCanInvite;
                                emGroup = EMClient.getInstance().groupManager().createGroup(name, getString(R.string.Introduction), members, "",
                                        option);
                        UpdateGroupAvatarJson updateGroupAvatarJson1 = new UpdateGroupAvatarJson(
                                emGroup.getGroupId());
                        getGroupAvatarRequest(Constants.AddChatCroupsImg,
                                updateGroupAvatarJson1);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                startActivity(new Intent(
                                        GroupPickContactsActivity.this,
                                        GroupsActivity.class));
                                finish();
                            }
                        });
                    } catch (final HyphenateException e) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(GroupPickContactsActivity.this,
                                        st2 + e.getLocalizedMessage(), 1)
                                        .show();
                            }
                        });
                    }

                }

            }).start();
        } else {
            setResult(RESULT_OK, new Intent().putExtra("newmembers",
                    getToBeAddMembers().toArray(new String[0])));
            finish();
        }
    }

    /**
     * 获取要被添加的成员
     * 
     * @return
     */
    private List<String> getToBeAddMembers() {
        List<String> members = new ArrayList<String>();
        int length = contactAdapter.isCheckedArray.length;
        for (int i = 0; i < length; i++) {
            String username = contactAdapter.getItem(i).getUsername();
            if (contactAdapter.isCheckedArray[i]
                    && !exitingMembers.contains(username)) {
                members.add(username);
            }
        }

        return members;
    }

    /**
     * adapter
     */
    public class PickContactAdapter extends ContactAdapter {

        private boolean[] isCheckedArray;

        public PickContactAdapter(Context context, int resource,
                                  List<FriendsUser> users) {
            super(context, resource, users);
            isCheckedArray = new boolean[users.size()];
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            // if (position > 0) {
            final String username = getItem(position).getUsername();
            // 选择框checkbox
            final CheckBox checkBox = (CheckBox) view
                    .findViewById(R.id.checkbox);
            if (exitingMembers != null && exitingMembers.contains(username)) {
                checkBox.setButtonDrawable(
                        R.drawable.checkbox_bg_gray_selector);
            } else {
                checkBox.setButtonDrawable(R.drawable.checkbox_bg_selector);
            }
            if (checkBox != null) {
                checkBox.setOnCheckedChangeListener(
                        new OnCheckedChangeListener() {
                            @Override
                            public void onCheckedChanged(
                                    CompoundButton buttonView,
                                    boolean isChecked) {
                                // 群组中原来的成员一直设为选中状态
                                if (exitingMembers.contains(username)) {
                                    isChecked = true;
                                    checkBox.setChecked(true);
                                } else {
                                    if (isChecked) {
//                                        Log.i(TAG, "选择的用户：" + getItem(position)
//                                                .getUsername());
                                        members.add(getItem(position)
                                                .getUsername());
                                        avatarSize = avatarSize + 1;
                                        // mHorizontalListViewAdapter
                                        // .notifyDataSetChanged();
                                        // mHlvAvatar.setSelection(
                                        // members.size() - 1);

                                    } else {
                                        members.remove(getItem(position)
                                                .getUsername());
                                        avatarSize = avatarSize - 1;
                                        // mHorizontalListViewAdapter
                                        // .notifyDataSetChanged();
                                        // mHlvAvatar.setSelection(
                                        // members.size() - 1);
                                    }
                                }

                                isCheckedArray[position] = isChecked;
                                // 如果是单选模式
                                if (isSignleChecked && isChecked) {
//                                    Log.i(TAG, "单选模式："
//                                            + getItem(position).getUsername());
                                    for (int i = 0; i < isCheckedArray.length; i++) {
                                        if (i != position) {
                                            isCheckedArray[i] = false;
                                        }
                                    }
                                    contactAdapter.notifyDataSetChanged();
                                }
                            }
                        });
                // 群组中原来的成员一直设为选中状态
                if (exitingMembers.contains(username)) {
                    checkBox.setChecked(true);
                    isCheckedArray[position] = true;
                } else {
                    checkBox.setChecked(isCheckedArray[position]);
                }
            }
            // }
            return view;
        }

    }

    public void back(View view) {
        finish();
    }

    /**
     * 获取群组头像
     * 
     * @param getGroupAvatarUrl
     * @param
     */
    private void getGroupAvatarRequest(String getGroupAvatarUrl,
            UpdateGroupAvatarJson mUpdateGroupAvatarJson) {
        Log.i(TAG,
                "<getGroupAvatarRequest>--<onResponse>--上传的JSon数据：  GetTokenJson = "
                        + mUpdateGroupAvatarJson);
        java.lang.reflect.Type type = new TypeToken<BaseResult>() {
        }.getType();
        JsonListRequest<BaseResult> request = new JsonListRequest<BaseResult>(
                mContext, Method.POST, getGroupAvatarUrl,
                mUpdateGroupAvatarJson.toString(), null, null, type, false,
                new Listener<BaseResult>() {

                    @Override
                    public void onResponse(BaseResult arg0) {
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        String data = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        data = (String) arg0.getData();
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  data = "
                                        + data);
                        if (code == 0) {
                            if (data != null) {
                                getGroupAvatarByUsernameBean mgetGroupAvatarByUsernameBean = new getGroupAvatarByUsernameBean(
                                        mContext);
                                mgetGroupAvatarByUsernameBean
                                        .setGroupid(emGroup.getGroupId());
                                mgetGroupAvatarByUsernameBean
                                        .setGroupname(emGroup.getGroupName());
                                mgetGroupAvatarByUsernameBean.setImage(data);
                                userDao.saveGroupAvatar(
                                        mgetGroupAvatarByUsernameBean);
                            }
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        NetworkResponse response = arg0.networkResponse;
                        if (response != null) {
                            try {
                                String json = new String(response.data,
                                        HttpHeaderParser.parseCharset(
                                                response.headers));
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- json = "
                                                + json);
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- response.data = "
                                                + response.data);
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- response.headers = "
                                                + response.headers);
                                // showToast(mContext, json,
                                // Toast.LENGTH_SHORT);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (arg0 != null && arg0.toString().contains(
                                "com.android.volley.NoConnectionError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.network_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.ServerError")) {
//                            Toast.makeText(mContext,
//                                    getString(
//                                            R.string.service_temporarily_unavailable),
//                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.TimeoutError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.time_out_error),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext,
                                    getString(R.string.request_fail),
                                    Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                        + arg0);
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse>--服务器请求失败： response = "
                                        + response);
                    }

                });
        VolleyUtil.addRequest(request);
    }
}
